<?php

namespace App\Dao;

use App\Constants\IncomeType;
use App\Model\Backpack;
use App\Model\IncomeExpense;
use App\Model\User;
use App\Model\UserVip;
use App\Utils\FunUtil;
use App\Utils\MemcacheClient;
use Hyperf\Context\ApplicationContext;
use Hyperf\DbConnection\Db;

class BackpackDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }


    /**
     * Note - 发放奖励到背包
     * DateTime 2024/8/12 12:54
     * User Admin
     * @param $uid
     * @param $reward
     * @param array $params
     */
    public function reward($uid, $reward, array $params = [])
    {
        // $userModel = new UserModel();
        switch ($reward['type']) {
            case 0: //礼物
                // $data = $this->find('*','type = ? and uid = ? and gift_id = ?',[0, $uid, $reward['gift_id']]);
                $data = User::query()->where('type', 0)->where('gift_id', $reward['gift_id'])->where('uid', $uid)->first();
                if (empty($data)) {
                    $arr = array(
                        'uid' => $uid,
                        'type' => 0,
                        'gift_id' => $reward['gift_id'],
                        'num' => $reward['num'],
                        'name' => $reward['name'],
                        'photo_url' => $reward['photo_url'],
                    );
                    Backpack::query()->insert($arr);
                    // $this->insert($arr);
                } else {
                    // $this->update($data['id'],['num'=>$data['num']+$reward['num']]);
                    Backpack::query()->where('id', $data['id'])->update(['num' => $data['num'] + $reward['num']]);
                }
                break;
            case 1://金币
                // $gift_count = $userModel->value($uid, 'gift_count');
                $gift_count = User::query()->where('id', $uid)->value('gift_count');
                IncomeExpense::query()->insert([
                    'uid' => $uid,
                    'type' => 1,
                    'sub_type' => IncomeType::SIGN_IN,
                    'amount_type' => 1,
                    'amount' => $reward['num'],
                    'account' => $gift_count + $reward['num'],
                    'ctime' => time(),
                    'from' => $params['from'] ?? 0,
                    'ip' => FunUtil::getClientIp(),
                    'version_code' => $params['version_code'] ?? '',
                    'package' => $params['package'] ?? '',
                    'channel' => $params['channel'] ?? ''
                ]);

                // 签到金币计入系统赠送金币
                if ($params['version_code'] >= 125) {
                    // $userModel->updateByWhereSet("sys_send_count=sys_send_count+{$reward['num']}", "id={$uid}");
                    User::query()->where('id', $uid)->update([
                        'sys_send_count' => Db::raw('sys_send_count+' . $reward['num'])
                    ]);
                } else {
                    // $userModel->updateUserGoldCount($uid, $reward['num']);
                    // 更新用户金币数量
                    UserDao::getInstance()->addUserGoldCount($uid, $reward['num']);

                }
                MemcacheClient::getInstance()->delete("userInfo_" . $uid);
                break;
            case 2://vip体验券
                $user = UserDao::getInstance()->findUserInfoCache($uid);
                $userVipModel = new UserVip();
                if ($user['noble'] == 1) {
                    //写入tb_user_vip
                    // $data1 = $userVipModel->find('*', 'uid = ? and status = ?', [$uid, 1]);
                    // $insertData['etime'] = $data1['etime'] + 86400 * $reward['num'];
                    // $userVipModel->update($data1['id'], $insertData);
                    $userVipModel->newQuery()->where('uid', $uid)->where('status', 1)->update([
                        'etime' => Db::raw('etime+' . 86400 * $reward['num'])
                    ]);
                } else {
                    // $userVipParams = array('noble' => '1');
                    // $userModel->update($uid, $userVipParams);
                    User::query()->where('id', $uid)->update(['noble' => '1']);
                    $insertData['uid'] = $uid;
                    $insertData['order_id'] = '';
                    $insertData['type'] = 25;
                    $insertData['day'] = 1;
                    $insertData['ctime'] = time();
                    $insertData['status'] = 1;
                    $insertData['etime'] = time() + 86400 * $reward['num'];
                    $userVipModel->newQuery()->insert($insertData);
                }
                MemcacheClient::getInstance()->delete("userInfo_" . $uid);
                break;
            default://其他
        }
    }

    /**
     * Note - 扣除用户的背包礼物数量
     * DateTime 2024/8/12 12:53
     * User Admin
     * @param $uid
     * @param $gid
     * @param $num
     * @return int
     */
    public function reduceUserGiftNum($uid, $gid, $num)
    {
        // $sql = "update {$this->table} set num = num - ? where uid = ? and gift_id =? and num>0";
        // $pd = $this->createCommand($sql);
        // $pd->execute(array($num, $uid, $gid));
        // return $pd->rowCount();
        return Backpack::query()->where('uid', $uid)->where('gift_id', $gid)->where('num', '>', 0)->decrement('num', $num);
    }

}